#include "login.h"
#include "ui_login.h"

Login::Login(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::Login)
{
    ui->setupUi(this);

    init();//调用程序初始化函数
}

Login::~Login()
{
    delete ui;
}

void Login::init()
{
    //初始化数据库连接,并设置连接参数
    g_db=QSqlDatabase::addDatabase("QMYSQL");//设置数据库驱动
    g_db.setDatabaseName(g_dbName);//设置数据库名称
    g_db.setUserName(g_dbUserName);//设置数据库用户名
    g_db.setPassword(g_dbUserPswd);//设置用户密码
    g_db.setHostName("localhost");//设置连接主机,端口默认3306

    if(!g_db.open()){//尝试打开数据库,如果打开失败则发出提示
        QMessageBox::warning(this,"警告","数据库打开失败.");
        return;
    }

    //如果打开数据库成功,则尝试创建数据表
    QSqlQuery query(g_db);

    //创建学生表
    query.exec(QString("create table if not exists %1("
                  "stu_id int primary key,"
                  "name varchar(20),"
                  "sex varchar(12),"
                  "birth date,"
                  "class float,"
                       "school varchar(50))").arg(g_tbStudent));

    //创建username表
    query.exec(QString("create table if not exists %1("
               "username varchar(20),"
               "password varchar(12),"
                       "aut date);").arg(g_tbUsername));

    //插入收数据
    query.exec("insert into student values"
               "(101,'张大','男','1978-5-8',3000.00,'外国语大学'),"
               "(102,'张二','男','1986-6-9',4500.00,'西安市莲湖区'),"
               "(103,'张三','女','1990-2-2',6000.00,'西安市碑林区')");

}

void Login::on_btnQuit_clicked()
{
    //关闭程序
    this->close();

}


void Login::on_btnLogin_clicked()
{
    //获取登录界面输入的账号和密码
    QString account=ui->editAccount->text();
    QString pswd=ui->editPswd->text();

    if(account.isEmpty()||pswd.isEmpty()){//如果账号或密码为空,则发出提示
        QMessageBox::warning(this,"警告","请输入完整的登录信息!");
        return;
    }

    //查询账号密码是否存在
    QSqlQuery query(g_db);
    query.exec(QString("select * from %1 where username='%2';").arg(g_tbUsername,account));//按账号查询密码
    query.first();//切换至第一条查询到的记录
    if(query.isValid()){//如过记录可用,则账号输入正确,开始进行密码校验
        if(query.value("password").toString()==pswd){//如果密码校验正确则进入系统
            g_userName=account;//设置用户名全局变量值
            MainWindow* m=new MainWindow();//初始化系统界面类
            m->show();//显示系统界面
            this->hide();//隐藏登录界面
        }else{//如果密码校验错误则发出提示
            QMessageBox::warning(this,"警告","密码错误!");
            return;
        }

    }else{//如果记录不可用,则提示账号输入错误
        QMessageBox::warning(this,"警告","账号输入错误!");
        return;
    }
}

